package dominioDAO;

import hbt.HibernateDAO;
import hbt.HibernateUtil;

import java.rmi.RemoteException;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import dominioEntity.Proveedor;
import dominioTO.ProveedorTO;

public class ProveedorDAO {
	private static ProveedorDAO instancia ;
	private static SessionFactory sf;
	private static Session session;
	
	public static ProveedorDAO getInstancia() {
		if(instancia == null){
			instancia = new ProveedorDAO();
		} 
		return instancia;
	}
	public ProveedorDAO()
	{
		sf = HibernateUtil.getSessionFactory();
	}
	
	protected Session getSession(){
		if(session == null || !session.isOpen()){
			session = sf.openSession();
		}
		return session;
	}
	protected void closeSession()
	{
		if(session.isOpen())
		{
			session.close();
		}
	}
	
	public void persistirProveedor(List<ProveedorTO> list) throws RemoteException
	{		
		
		for(ProveedorTO dto : list){
			
			if(this.buscarProveedor(dto.getCuit())==null )
			{
			Proveedor aux = new Proveedor ();
			
			aux.setCuit(dto.getCuit());
			aux.setNombre(dto.getNombre());
			aux.setDireccion(dto.getDireccion());
			aux.setTelefono(dto.getTelefono());			
			this.grabarSolicitud(aux);
			}
		}
			
	}
	
	
	public Proveedor buscarProveedor(String cuit)
	{
		Proveedor aux = new Proveedor();
		aux.setCuit(cuit);
		
		String query = "from Proveedor where cuit=:cuit";
		Proveedor prov = (Proveedor) HibernateDAO.getInstancia().propiedades(query, aux);
		return prov;
	}
	public void grabarSolicitud(Proveedor p) {
		
		Session s = this.getSession();
		s.beginTransaction();
		s.saveOrUpdate(p);
		s.flush();
		session.getTransaction().commit();
		this.closeSession();

	}
	
	
}
